export default class WxCanvas {
	public canvasId: string;
	public event = {} as any;
	public chart: any;
	public ctx: any;
	constructor(ctx: any, canvasId: string) {
		this.ctx = ctx;
		this.canvasId = canvasId;
		this.chart = null;

		// this._initCanvas(zrender, ctx);
		this._initStyle(ctx);
		this._initEvent();
	}

	public getContext(contextType: '2d') {
		if (contextType === '2d') {
			return this.ctx;
		}
	}

	// canvasToTempFilePath(opt) {
	//   if (!opt.canvasId) {
	//     opt.canvasId = this.canvasId;
	//   }

	//   return wx.canvasToTempFilePath(opt, this);
	// }

	public setChart(chart: any) {
		this.chart = chart;
	}

	public attachEvent() {
		// noop
	}

	public detachEvent() {
		// noop
	}

	// private _initCanvas(zrender: any, ctx: any) {
	// 	zrender.util.getContext = () =>  {
	// 		return ctx;
	// 	};

	// 	zrender.util.$override('measureText', (text: string, font: any) =>  {
	// 		ctx.font = font || '12px sans-serif';
	// 		return ctx.measureText(text);
	// 	});
	// }

	private _initStyle(ctx: any) {
		const styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
			'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
			'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'];

		styles.forEach((style) => {
			Object.defineProperty(ctx, style, {
				set: (value) => {
					if (style !== 'fillStyle' && style !== 'strokeStyle'
						|| value !== 'none' && value !== null
					) {
						ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
					}
				}
			});
		});

		ctx.createRadialGradient = () => {
			return ctx.createCircularGradient(arguments);
		};
	}

	private _initEvent() {
		this.event = {};
		const eventNames = [{
			ecName: 'mousedown',
			wxName: 'touchStart'
		}, {
			ecName: 'mousemove',
			wxName: 'touchMove'
		}, {
			ecName: 'mouseup',
			wxName: 'touchEnd'
		}, {
			ecName: 'click',
			wxName: 'touchEnd'
		}];

		eventNames.forEach((name) => {
			this.event[name.wxName] = (e: any) => {
				const touch = e.touches[0];
				this.chart._zr.handler.dispatch(name.ecName, {
					zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
					zrY: name.wxName === 'tap' ? touch.clientY : touch.y
				});
			};
		});
	}
}
